import { initScene } from "./initScene";
import {phy } from 'phy-engine'
import { Vector2, Vector3, type Scene, type WebGLRenderer } from "three";
const engine = 'OIMO';
// 目前来说，用phy这个库，就得在public目录下把build文件夹复制过来

function initEngine(scene:Scene,renderer:WebGLRenderer, callback:()=>void) {
    phy.init({
        type: engine,
        worker:false,
        scene,
        renderer,
        callback,
        usePmrem:true
        
    })
}

export function initPhy(container: HTMLElement) {
    const stage = initScene({
        cube: true,
        directLight: 1,
    })

    container.appendChild(stage.renderer.domElement)
    stage.resize()
    stage.loopRender()
    let stamp1 = performance.now()
    stage.afterRender = ()=>{
        phy.doStep(performance.now()- stamp1 )
    }
    const mousePoint = new Vector3(),worldPos = new Vector3();
    container.addEventListener('dblclick',(e)=>{
        mousePoint.set( ( e.clientX / container.clientWidth ) * 2 - 1, - ( e.clientY /container.clientWidth ) * 2 + 1 ,0);
        mousePoint.unproject(stage.camera);
        phy.add({type:'sphere',pos:mousePoint.toArray(),radius:0.5,visible:true})
    })

    initEngine(stage.scene, stage.renderer, () => {
        phy.set({substep:2,gravity:[0,-9.8,0],fps:60})
        phy.add({type:'plane',size:[300,1,300],material:'shadow',visible:true})
        phy.add({type:'box',size:[1,1,1],pos:[0,10,0],mass:1,visible:true})
        phy.activeMouse(stage.controls);

        console.log('%cphy-engine 初始化完成','color:green;font-size:16px;font-weight:bold;')
    })

}

